//
//  FANComposeViewController.m
//  Weibo - OC
//
//  Created by user on 16/4/26.
//  Copyright © 2016年 user. All rights reserved.
//

#import "FANComposeViewController.h"
#import "FANUserAccountModel.h"
#import "FANTextView.h"
#import "FANAddPictureView.h"
#import "UIImage+Extension.h"
#import "NetworkTools.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import "FANEmoticonView.h"
#import "FANEmoticon.h"
#import "NSString+Emoji.h"
#import "UITextView+Extension.h"

//#warning 宏定义一定要放到 导入头文件的 上面, 会影响编译

//define this constant if you want to use Masonry without the 'mas_' prefix

#define MAS_SHORTHAND

//define this constant if you want to enable auto-boxing for default syntax

#define MAS_SHORTHAND_GLOBALS

#import <Masonry/Masonry.h>
#import "FANStackTools.h"

@interface FANComposeViewController ()<UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) UILabel *titleView;

@property (nonatomic, strong) UIButton *rightButton;

@property (nonatomic, strong) FANTextView *textView;

@property (nonatomic, strong)FANStackTools *stackTools;

@property (nonatomic, strong) FANAddPictureView *addPictureView;

@property (nonatomic, strong) FANEmoticonView *emoticonView;

@end

@implementation FANComposeViewController

- (FANEmoticonView *)emoticonView{
    
    if (!_emoticonView) {
        
        _emoticonView = [[FANEmoticonView alloc] initWithFrame:CGRectZero];
        
        _emoticonView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 216);
        
    }
    
    return _emoticonView;
}

- (FANAddPictureView *)addPictureView{
    
    if (!_addPictureView) {
        
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        
        _addPictureView = [[FANAddPictureView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        
        _addPictureView.hidden = true;
        
        __weak typeof(self) weakSelf = self;
        
        _addPictureView.addBlock = ^{
        
            [weakSelf selectedPicture];
            
        };
    }
    
    return _addPictureView;
}

- (FANStackTools *)stackTools{
    
    if (!_stackTools) {
        
        _stackTools = [[FANStackTools alloc] initWithFrame:CGRectZero];
        
        __weak typeof(self) weakSelf = self;

        _stackTools.StackBlock = ^(FANComposeToolsType type){
            
//            NSLog(@"%ld",type);
            
            /*
             Picture = 0,
             Mention,
             Trend,
             Emoticon,
             Add,
             */
            
            
            switch (type) {
                case Picture:
                {
                    
                    [weakSelf selectedPicture];
                }
                    
                    break;
                case Mention:
                {
                    
                    
                }
                    
                    break;
                case Trend:
                {
                    
                    
                }
                    
                    break;
                case Emoticon:
                {
                    
                    [weakSelf didEmoticonClick];
                }
                    
                    break;
                case Add:
                {
                    
                    
                }
                    
                    break;
                    
                default:
                    break;
            }
            
        };
    }
    
    return _stackTools;
}

- (void)didEmoticonClick{
        
    if (self.textView.inputView == nil) {
        
        self.textView.inputView = self.emoticonView;
        
        self.stackTools.isKeyBoard = false;

    }else{
        
        self.textView.inputView = nil;
        
        self.stackTools.isKeyBoard = true;
    }
    
    [self.textView reloadInputViews];
}

- (void)selectedPicture{
    
    UIImagePickerController *pickerVc = [[UIImagePickerController alloc] init];
    
    pickerVc.delegate = self;
    
    [self presentViewController:pickerVc animated:true completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo{
    
    [self.addPictureView addImageMethod:[image scaleInWidth:600]];
    
    [picker dismissViewControllerAnimated:true completion:nil];
    
}

-(FANTextView *)textView{
    
    if (!_textView) {
        
        _textView = [[FANTextView alloc] init];
        
        _textView.font = [UIFont systemFontOfSize:14];
        
        _textView.delegate = self;
        
        _textView.placeHolder = @"分享新鲜事...";
        
        _textView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        
        _textView.alwaysBounceVertical = false;
        
    }
    return _textView;
}

- (UIButton *)rightButton{
    
    if (!_rightButton) {
        
        _rightButton = [[UIButton alloc] init];
        
        _rightButton.titleLabel.font = [UIFont systemFontOfSize:14];
        
        [_rightButton setTitle:@"发送" forState:UIControlStateNormal];
        
        [_rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_rightButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateDisabled];
        
        [_rightButton setBackgroundImage:[UIImage imageNamed:@"common_button_white_disable"] forState:UIControlStateDisabled];
        
        [_rightButton setBackgroundImage:[UIImage imageNamed:@"common_button_orange"] forState:UIControlStateNormal];

        [_rightButton setBackgroundImage:[UIImage imageNamed:@"common_button_orange_highlighted"] forState:UIControlStateHighlighted];
        
        [_rightButton addTarget:self action:@selector(sendWeibo) forControlEvents:UIControlEventTouchUpInside];

        CGRect rect = _rightButton.frame;
        
        rect.size = CGSizeMake(48, 25);
        
        _rightButton.frame = rect;
    }
    
    return _rightButton;
}

- (UILabel *)titleView{
    
    if (!_titleView) {
        
        _titleView = [[UILabel alloc] init];
        
        _titleView.numberOfLines = 0;
        
        _titleView.textAlignment = NSTextAlignmentCenter;
        
        _titleView.font = [UIFont systemFontOfSize:15];
        
        _titleView.textColor = [UIColor blackColor];
        
        NSString *name = [FANUserAccountModel sharedAccountModel].account.name;
        
        if (name != nil) {
            
            NSString *text = [NSString stringWithFormat:@"发微博\n%@",name];
            
            NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:text];
            
            NSRange range = [text rangeOfString:name];
            
            [attr setAttributes:@{NSForegroundColorAttributeName:[UIColor darkGrayColor],NSFontAttributeName:[UIFont systemFontOfSize:12]} range:range];
            
            _titleView.attributedText = attr;
            
        }else{
            
            _titleView.text = @"发微博";
        }
        
        [_titleView sizeToFit];

    }
    
    return  _titleView;
}

- (void)sendWeibo{
    
    if (self.addPictureView.hidden) {
        
        [self sendTextWeibo];
    }else{
        
        [self sendImageWeibo];
    }
}


- (void)sendImageWeibo{
    
    NSString *urlString = @"https://upload.api.weibo.com/2/statuses/upload.json";
    
    NSDictionary *params = @{
                             
         @"access_token": [FANUserAccountModel sharedAccountModel].account.access_token,
         @"status": self.textView.emoticonText
    };
    
    NSData *data = UIImagePNGRepresentation(self.addPictureView.imageArray.firstObject);
    
    [[NetworkTools sharedTools] upload:urlString and:@{@"pic":data} andParameter:params andBlock:^(id responseObject, NSError *error) {
       
        if (error == nil) {
            
            [SVProgressHUD showSuccessWithStatus:@"发送成功"];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self back];

            });
            
        }else{
            
            [SVProgressHUD showErrorWithStatus:@"发送失败"];
        }
        
        
        
    }];
    
}

- (void)sendTextWeibo{
    
    NSString *urlString = @"https://api.weibo.com/2/statuses/update.json";
    
    NSDictionary *params = @{
    
        @"access_token": [FANUserAccountModel sharedAccountModel].account.access_token,
        @"status": self.textView.emoticonText
    };
    
    
    [[NetworkTools sharedTools] request:FANRequestMethodPost andUrlString:urlString andParameter:params andBlock:^(id responseObject, NSError *error) {
        
        if (error == nil) {
            
            [SVProgressHUD showSuccessWithStatus:@"发送成功"];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self back];
                
            });
        
        }else{
            
            [SVProgressHUD showErrorWithStatus:@"发送失败"];
        }
        
        
    }];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupUI];
    
}

- (void)textViewDidChange:(UITextView *)textView{
    
    self.rightButton.enabled = self.textView.hasText;
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    [self.textView becomeFirstResponder];
    
    if (!self.addPictureView.hidden) {
        
        [self.textView resignFirstResponder];
        
    }

}

- (void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    
   
    
//    [self.textView becomeFirstResponder];
}

- (void)setupUI{
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.textView];
    
    [self.textView addSubview:self.addPictureView];
    
    [self.textView makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(self.view);
        
    }];
    
    [self.view addSubview:self.stackTools];
    
    [self.stackTools makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.trailing.leading.equalTo(self.view);
        
        make.height.equalTo(44);
        
    }];
    
    [self.addPictureView makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.equalTo(100);
        
        make.leading.trailing.equalTo(5);
        
        make.width.equalTo(self.textView.width).offset(-10);
        
        make.height.equalTo(self.addPictureView.width);
        
    }];
    
    [self setupNav];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEmoticonClick:) name:@"FANDidEmoticonButtonNotification" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didDelectedClick) name:@"FANDidDelectedClickNotification" object:nil];
}

- (void)didDelectedClick{
    
    [self.textView deleteBackward];
}

- (void)didEmoticonClick:(NSNotification *)noti{
    
    FANEmoticon *emoticon = noti.userInfo[@"emoticon"];
    
    if ([emoticon.type isEqualToString:@"1"]) {
        
        [self.textView insertText:[emoticon.code emoji]];
        
    }else{
        
        [self.textView insertEmoticon:emoticon];
    }
}

- (void)keyboardChange:(NSNotification *)noti{
    
    /*
     2016-04-27 11:23:55.804 Weibo - OC[1439:16846] NSConcreteNotification 0x7fa23b0c34f0 {name = UIKeyboardWillChangeFrameNotification; userInfo = {
     UIKeyboardAnimationCurveUserInfoKey = 7;
     UIKeyboardAnimationDurationUserInfoKey = "0.25";
     UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
     UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
     UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
     UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
     UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
     UIKeyboardIsLocalUserInfoKey = 1;
     }}
     */
    
//    NSLog(@"%@",noti);
    
    
    NSValue *v = (NSValue *)noti.userInfo[UIKeyboardFrameEndUserInfoKey];
    
    CGRect endRect = [v CGRectValue];
    
    [self.stackTools updateConstraints:^(MASConstraintMaker *make) {
       
        make.bottom.equalTo(endRect.origin.y - [UIScreen mainScreen].bounds.size.height);
        
    }];
    
    [UIView animateWithDuration:0.25 animations:^{
        
        [self.view layoutIfNeeded];
        
    }];
}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setupNav{
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    
    [self.navigationItem.leftBarButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor orangeColor]} forState:UIControlStateNormal];
    
    self.navigationItem.titleView = self.titleView;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    
    self.navigationItem.rightBarButtonItem.enabled = false;
}

- (void)back{
    
    [self.textView resignFirstResponder];
    
    [self dismissViewControllerAnimated:true completion:nil];
}

@end
